#include "List.h"


List::List()
	: first(NULL)
{
}

List::~List()
{
	Node *current = first;
	Node *previous = first;
	
	while(current != NULL)
	{
		previous = current;
		current = previous->getNext();
		delete previous;
	}
}

void List::addFirst(Data* data)
{
	Node* nodo = new Node();

	nodo->setData(data);
	nodo->setNext(first);
	first = nodo;
}

void List::add(Data* data)
{	
	Node* nodo = new Node();
	Node* current = first;
	Node* previous = first;

	nodo->setData(data);

	while(current != NULL)
	{
		previous = current;
		current = previous->getNext();
	}
	if(previous == NULL) 
	{
		// La lista esta vacia
		first = previous = nodo;
	}
	else
		previous->setNext(nodo);
}

void List::remove(Data* data)
{	
	Node* current = first;
	Data* currentData = NULL;
	Node* previous = first;
	
	currentData = current->getData();
	if(currentData->equal(data))
	{
		first=current->getNext();	
		delete current;
	}
	else
	{
		while(current != NULL)
		{
			previous = current;
			current = previous->getNext();
			if(current != NULL)
			{
				currentData = current->getData();
				if(currentData->equal(data))
				{
					previous->setNext(current->getNext());
					delete current;
					current = NULL;
				}
			}
		}
	}
}

void List::removeLast()
{
	Node* current = first;	
	Node* previous = first;
	
	while(current != NULL)
	{
		previous = current;
		current = previous->getNext();
	}
	if(previous != NULL)
		delete previous;
}

bool List::get(Data* data)
{
	Node* current = first;
	Data* currentData = NULL;
	Node* previous = first;
	
	while(current != NULL)
	{
		previous = current;
		current = previous->getNext();
		
		
		currentData = previous->getData();
		if(currentData->equal(data))
		{
			currentData->copy(&data);
			return true;
		}
		
	}
	return false;
}

bool List::isEmpty()
{
	return (first == NULL);
}



